/**
 * Copyright (C) 2018-2021
 * All rights reserved, Designed By www.yixiang.co
 * 注意：
 * 本软件为www.yixiang.co开发研制，未经购买不得使用
 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
 */
package co.yixiang.modules.distributor.service.impl;

import co.yixiang.common.service.impl.BaseServiceImpl;
import co.yixiang.dozer.service.IGenerator;
import co.yixiang.modules.distributor.domain.DistributorPrice;
import co.yixiang.modules.distributor.domain.YxDistributor;
import co.yixiang.modules.distributor.service.DistributorPriceService;
import co.yixiang.modules.distributor.service.mapper.DistributorPriceMapper;
import co.yixiang.modules.distributor.service.mapper.YxDistributorMapper;
import co.yixiang.modules.distributor.vo.DistributorPriceDto;
import co.yixiang.modules.distributor.vo.DistributorPriceVo;
import co.yixiang.modules.product.service.YxStoreProductAttrValueService;
import co.yixiang.modules.product.service.dto.SkuProductDto;
import co.yixiang.modules.product.service.mapper.StoreProductAttrValueMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageInfo;
import com.qiniu.util.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;

/**
 * @author ysl
 * @date 2021-11-21
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DistributorPriceServiceImpl extends BaseServiceImpl<DistributorPriceMapper, DistributorPrice> implements DistributorPriceService {

    @Autowired
    private IGenerator generator;

    @Autowired
    private DistributorPriceMapper distributorPriceMapper;

    @Autowired
    private StoreProductAttrValueMapper storeProductAttrValueMapper;

    @Autowired
    private YxDistributorMapper yxDistributorMapper;

    @Autowired
    private YxStoreProductAttrValueService yxStoreProductAttrValueService;

    @Override
    public List<DistributorPrice> queryByDistributorIdAndProductId(String distributorId, Long productId) {
        LambdaQueryWrapper<DistributorPrice> wrapper = new LambdaQueryWrapper<>();
        if (!StringUtils.isNullOrEmpty(distributorId)) {
            wrapper.eq(DistributorPrice::getDistributorId, distributorId);
        }

        if (Long.valueOf(productId) > 0) {
            wrapper.eq(DistributorPrice::getProductId, productId);
        }

        return this.list(wrapper);
    }


    @Override
    public Map<String, Object> queryDistributorPricesByDisId(String id, Pageable pageable) {
        getPage(pageable);
        List<DistributorPriceVo> distributorPrices = queryByDisId(id);
        PageInfo<DistributorPriceVo> page = new PageInfo<>(distributorPrices);
        Map<String, Object> map = new LinkedHashMap<>(2);
        map.put("content", generator.convert(page.getList(), DistributorPriceVo.class));
        map.put("totalElements", page.getTotal());
        return map;
    }


    public List<DistributorPriceVo> queryByDisId(String id) {
        List<DistributorPriceVo> vos = storeProductAttrValueMapper.selectAllSkuAndProducts(-1);
        List<DistributorPriceDto> dtos = distributorPriceMapper.queryDistributorPricesByDisId(id);
        YxDistributor yxDistributor = null;
        if (dtos == null || dtos.size() == 0) {
            yxDistributor = yxDistributorMapper.getYxDistributorByDistributorId(id);
        }
        Map<Long, DistributorPriceDto> dtoMap = new HashMap<Long, DistributorPriceDto>();
        for (DistributorPriceDto dto : dtos) {
            dtoMap.put(dto.getProductSku(), dto);
        }

        //重塑distributorPriceVos
        for (DistributorPriceVo vo : vos) {
            vo.setId("");
            if (dtos == null || dtos.size() == 0) {
                vo.setDistributorId(yxDistributor.getDistributorId());
                vo.setDistributorName(yxDistributor.getDistributorName());
            } else {
                vo.setDistributorId(dtos.get(0).getDistributorId());
                vo.setDistributorName(dtos.get(0).getDistributorName());
                if (dtoMap.get(vo.getProductSku()) != null) {
                    DistributorPriceDto dto = dtoMap.get(vo.getProductSku());
                    vo.setId(dto.getId());
                    vo.setDiscount(dto.getDiscount());
                    vo.setTradePrice(dto.getTradePrice());
                    vo.setCreater(dto.getCreater());
                    vo.setCreateTime(dto.getCreateTime());
                    vo.setInvoiceType(dto.getInvoiceType());
                    vo.setIncludeDeliveryFee(dto.getIncludeDeliveryFee());
                    vo.setRemark(dto.getRemark());
                }
            }
        }
        return vos;
    }


    @Override
    public boolean addOrUpdate(DistributorPrice resources) {
        try{
            if (resources.getId() == null || resources.getId() == 0) {
                //表中没有这个报价，那么需要插入一条
                this.save(resources);
            } else {
                //后台需要更新的字段
                resources.setUpdateTime(new Date());
                //resources.setCreater();
                this.saveOrUpdate(resources);
            }
        }catch (Exception e){
            return false;
        }

        return true;
    }

    @Override
    public boolean delOrDoNothing(Integer id) {
        try {
            if (id != null && id != 0){
                this.removeById(id);
            } else {
                return true;
            }
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Override
    public Map<Long, List<DistributorPrice>> genProductPriceMap(String distributorId) {
        List<DistributorPrice> distributorPrices = this.queryByDistributorIdAndProductId(distributorId, 0L);
        Map<Long,List<DistributorPrice>> map = new HashMap<>();
        for (DistributorPrice distributorPrice : distributorPrices) {
            List<DistributorPrice> distributorPricesList = map.get(distributorPrice.getProductId());
            if (distributorPricesList == null) {
                distributorPricesList = new ArrayList<>();
                map.put(distributorPrice.getProductId(), distributorPricesList);
            }
            distributorPricesList.add(distributorPrice);
        }
        return map;
    }

    @Override
    public Map<Long, DistributorPrice> genProductMinPrice(String distributorId) {
        Map<Long, List<DistributorPrice>> map = this.genProductPriceMap(distributorId);

        Map<Long, DistributorPrice> minPriceMap = new HashMap<>();
        for (Map.Entry<Long, List<DistributorPrice>> entry : map.entrySet()) {
            DistributorPrice minDistributorPrice = entry.getValue().get(0);
            for (DistributorPrice distributorPrice : entry.getValue()) {
                if (minDistributorPrice.getTradePrice() > distributorPrice.getTradePrice()) {
                    minDistributorPrice = distributorPrice;
                }
            }

            if (minDistributorPrice.getTradePrice() <= 0L) {
                continue;
            }
            minPriceMap.put(minDistributorPrice.getProductId(), minDistributorPrice);
        }
        return minPriceMap;
    }
}
